package top.songxs.yygh.hosp.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.songxs.yygh.common.result.R;
import top.songxs.yygh.common.utils.JwtHelper;
import top.songxs.yygh.enums.AuthStatusEnum;
import top.songxs.yygh.model.user.UserInfo;
import top.songxs.yygh.hosp.user.constant.ConstantPropertiesUtil;
import top.songxs.yygh.hosp.user.service.UserInfoService;
import top.songxs.yygh.hosp.user.util.HttpClientUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller //注意：不是@RestController
@RequestMapping("/api/user/wx")
public class WeixinApiController {
    @Autowired
    UserInfoService userInfoService;

    //用户授权后
    @GetMapping("callback")
    public String callBack(String code){
        //code临时票据，重定向到第三方，携带临时票据
        //根据openid获取到改微信用户的昵称
        //判断数据库中user_info表是否存在该微信用户（根据openid查询一下） 如果不存在自动注册（添加一条数据到user_info）
        //重定向到前端的一个vue组件 https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        //并且传递三个参数，带三个参数给前端 accessTokenUrl


        Map<String,String > headers = new HashMap<>();
        Map<String,String > querys = new HashMap<>();
        querys.put("appid",ConstantPropertiesUtil.WX_OPEN_APP_ID);
        querys.put("secret",ConstantPropertiesUtil.WX_OPEN_APP_SECRET);
        querys.put("code",code);
        querys.put("grant_type","authorization_code");

        try {
            String  url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid="+ConstantPropertiesUtil.WX_OPEN_APP_ID+"" +
                    "&secret="+ConstantPropertiesUtil.WX_OPEN_APP_SECRET+"" +
                    "&code="+code+
                    "&grant_type=authorization_code";
            String s = HttpClientUtils.get(url);
            JSONObject jsonObject = JSON.parseObject(s);
            String token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

           UserInfo userInfo = userInfoService.getByOpenid(openid);
           if (userInfo == null){
               String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openid;
               String jsonString = HttpClientUtils.get(url2);
               JSONObject jsonObject1 = JSON.parseObject(jsonString);
               String nickname = jsonObject1.getString("nickname");
               userInfo = new UserInfo();
               userInfo.setAuthStatus(AuthStatusEnum.NO_AUTH.getStatus());
               userInfo.setNickName(nickname);
               userInfo.setOpenid(openid);
               userInfo.setStatus(1);
               userInfo.setCreateTime(new Date());
               userInfo.setUpdateTime(new Date());
               userInfoService.save(userInfo);

           }
            //6、返回name+token+openid（phone为空时返回openid）
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
                if(StringUtils.isEmpty(name)) {
                    name = userInfo.getPhone();
                }
            }

            String tok = JwtHelper.createToken(userInfo.getId(), name);

            return "redirect:http://localhost:3000/weixin/callback?" +
                    "name="+URLEncoder.encode(name,"utf-8")  +"&" +
                    "token="+tok + "&" +
                    "openid="+(StringUtils.isEmpty(userInfo.getPhone())?userInfo.getOpenid():"");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    //返回给前端二维码参数
    @ResponseBody
    @GetMapping("getLoginParam")
    public R genQrConnect() throws UnsupportedEncodingException {

        Map<String,Object> map = new HashMap<>();
        map.put("self_redirect",true);
        map.put("id","weixinLogin");
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("scope","snsapi_login");
        map.put("redirect_uri", URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,"utf-8"));

        return R.ok().data(map);
    }
}